<style>
    body {
        padding: 15px 10px
    }

    body .layui-form fieldset.layui-elem-field {
        margin: 0 0 10px 0
    }

    body .i18n-tran {
        cursor: pointer
    }
</style>
<script>
    // 表单
    layui.use(['element', 'form', 'upload', 'layedit', 'laydate', 'colorpicker', 'layer', 'util'], function () {
        var form = layui.form,
            upload = layui.upload,
            layedit = layui.layedit,
            laydate = layui.laydate,
            colorpicker = layui.colorpicker,
            layer = layui.layer,
            util = layui.util,
            $ = layui.jquery;

        // 临时翻译检查格式错误
        function chk_err() {
            var arr = [];
            if ($('form input[name="name"]').length && $('form input[name="name"]').val().indexOf('.') !== -1) {
                arr.push('Name');
            }
            if ($('form input[name="title"]').length && $('form input[name="title"]').val().indexOf('.') !== -1) {
                arr.push('Title');
            }
            if ($('select[name="category_id"]').length && !$('select[name="category_id"]').val()) {
                arr.push('Category');
            }
            if ($('input[name="tags"]').length && $('input[name="tags"]').val()) {
                arr.push('Tag')
            }
            if (typeof window.editor1 === 'undefined') return arr;
            var ori = '';
            if (typeof window.editor_1 !== 'undefined') {
                ori = window.editor_1.html();
            }
            var tmp = window.editor1.html();
            if (ori && !tmp) {
                arr.push('Content');
                return arr;
            }
            if (tmp.indexOf('&lt;') !== -1) {
                arr.push('&' + 'lt;');
            }
            if (tmp.indexOf('&gt;') !== -1) {
                arr.push('&' + 'gt;');
            }
            if (tmp.match(/color:\s*;/)) {
                arr.push('color:;');
            }
            if (tmp.match(/["']\s*=\s*["']/)) {
                arr.push('"="');
            }
            if (tmp.match(/<\s*--/)) {
                arr.push('<--');
            }
            if (tmp.match(/--\s*>/)) {
                arr.push('-->');
            }
            if ((tmp.match(/<div[^>]*>/gi) || '').length !== (tmp.match(/<\/div>/gi) || '').length) {
                arr.push('div');
            }
            if ((tmp.match(/<table[^>]*>/gi) || '').length !== (tmp.match(/<\/table>/gi) || '').length) {
                arr.push('table');
            }
            if ((tmp.match(/<p[^>]*>/gi) || '').length !== (tmp.match(/<\/p>/gi) || '').length) {
                arr.push('p');
            }
            var temp = tmp.match(/<p[^>]*>.+?<\/p>/gsim);
            var tags = ['strong', 'span'];
            if (temp && temp.length) {
                for (var i = 0; i < temp.length; i++) {
                    for (var j = 0; j < tags.length; j++) {
                        var tag1 = temp[i].match(new RegExp('<[^>\/]*' + tags[j] + '[^>]*>', 'gsim')) || '';
                        var tag2 = temp[i].match(new RegExp('<\/[^>]*' + tags[j] + '[^>]*>', 'gsim')) || '';
                        var tag3 = temp[i].match(new RegExp('<' + tags[j] + '[^>]*>[^<>]*<\/p>'), 'gsim') || '';
                        var tag4 = temp[i].match(new RegExp('<p>[^<>]*<\/' + tags[j] + '>'), 'gsim') || '';
                        var tag5 = temp[i].match(new RegExp('<' + tags[j] + '[^>]*>[^<>]*<' + tags[j] + '[^>]*>'), 'gsim') || '';
                        var tag6 = temp[i].match(new RegExp('<\/' + tags[j] + '>[^<>]*<\/' + tags[j] + '>'), 'gsim') || '';
                        if (tag1.length !== tag2.length || tag3 || tag4 || tag5 || tag6) {
                            arr.indexOf(tags[j] + '-' + (i + 1)) == -1 && arr.push(tags[j] + '-' + (i + 1));
                        }
                    }
                    var match = temp[i].match(/<\/*[^>\/]*>/g) || [];
                    if (match.length % 2 == 1) {
                        var tag = match[1].replace(/<|\/|>/g, '');
                        arr.indexOf(tag + '-' + (i + 1)) == -1 && arr.push(tag + '-' + (i + 1));
                    }
                    if ((temp[i].match(/</g) || '').length !== (temp[i].match(/>/g) || '').length) {
                        if ((temp[i].match(/</g) || '').length > (temp[i].match(/>/g) || '').length) {
                            arr.indexOf('<-' + (i + 1)) == -1 && arr.push('<' + '-' + (i + 1));
                        } else {
                            arr.indexOf('>-' + (i + 1)) == -1 && arr.push('>' + '-' + (i + 1));
                        }
                    }
                }
            }
            temp = tmp.match(/<table[^>]*>.+?<\/table>/gsim);
            tags = ['tbody', 'tr', 'td'];
            if (temp && temp.length) {
                for (var i = 0; i < temp.length; i++) {
                    for (var j = 0; j < tags.length; j++) {
                        var tag1 = temp[i].match(new RegExp('<[^>\/]*' + tags[j] + '[^>]*>', 'gsim')) || '';
                        var tag2 = temp[i].match(new RegExp('<\/[^>\/]*' + tags[j] + '[^>]*>', 'gsim')) || '';
                        var tag3 = temp[i].match(new RegExp('<' + tags[j] + '[^>]*>[^<>]*<\/table>'), 'gsim') || '';
                        var tag4 = temp[i].match(new RegExp('<table>[^<>]*<\/' + tags[j] + '>'), 'gsim') || '';
                        var tag5 = temp[i].match(new RegExp('<' + tags[j] + '[^>]*>[^<>]*<' + tags[j] + '[^>]*>'), 'gsim') || '';
                        var tag6 = temp[i].match(new RegExp('<\/' + tags[j] + '>[^<>]*<\/' + tags[j] + '>'), 'gsim') || '';
                        if (tag1.length !== tag2.length || tag3 || tag4 || tag5 || tag6) {
                            arr.indexOf(tags[j] + '-' + (i + 1)) && arr.push(tags[j] + '-' + (i + 1));
                        }
                    }
                    var match = temp[i].match(/<\/*[^>\/]*>/g) || [];
                    if (match.length % 2 == 1) {
                        var tag = match[1].replace(/<|\/|>/g, '');
                        arr.indexOf(tag + '-' + (i + 1)) == -1 && arr.push(tag + '-' + (i + 1));
                    }
                    if ((temp[i].match(/</g) || '').length !== (temp[i].match(/>/g) || '').length) {
                        if ((temp[i].match(/</g) || '').length > (temp[i].match(/>/g) || '').length) {
                            arr.indexOf('<-' + (i + 1)) == -1 && arr.push('<' + '-' + (i + 1));
                        } else {
                            arr.indexOf('>-' + (i + 1)) == -1 && arr.push('>' + '-' + (i + 1));
                        }
                    }
                }
            }
            return arr;
        }

        // 临时翻译修复格式错误
        function rep_err() {
            if ($('form input[name="name"]').length) {
                $('form input[name="name"]').val($('form input[name="name"]').val().replace(/\./g, ''));
            }
            if ($('form input[name="title"]').length) {
                $('form input[name="title"]').val($('form input[name="title"]').val().replace(/\./g, ''));
            }
            if (typeof window.editor1 === 'undefined') return false;
            // 格式修复
            var tmp = window.editor1.html();
            tmp = tmp.replace(/&emsp;/gi, ' ');
            tmp = tmp.replace(/&nbsp;/gi, ' ');
            tmp = tmp.replace(/(>\s*)[\?]+(\s*<)/g, '$1$2');
            tmp = tmp.replace(/\s*=\s*(["'])/g, '=$1');
            tmp = tmp.replace(/(["'])\s*:\s*(["'])/g, '$1:$2');
            tmp = tmp.replace(/:\s*#\s*/g, ':#');
            tmp = tmp.replace(/"\s*([^\":]*):\s*([^\";]*;)\s*"/g, '"$1:$2"');
            tmp = tmp.replace(/<\s*\/\s*([^>]*)>/g, '</$1>');
            tmp = tmp.replace(/>\s*>/g, '>');
            tmp = tmp.replace(/<\s*</g, '<');
            tmp = tmp.replace(/<[\s|\.]*>/g, ' ');
            tmp = tmp.replace(/\s*;[\.\s]*"\s*>/g, ';">');
            tmp = tmp.replace(/="([^\">]*);\s*>/g, '="$1;">');
            tmp = tmp.replace(/<strong>\s*<\/strong>/gi, ' ');
            tmp = tmp.replace(/<span[^>]*>\s*<\/span>/gi, ' ');
            tmp = tmp.replace(/(<p[^>]*>)\s*<br[^>]*>/gi, '$1');
            tmp = tmp.replace(/<br[^>]*>\s*(<\/p>)/gi, '$1');
            tmp = tmp.replace(/<p[^>]*>\s*<\/p>/gi, ' ');
            tmp = tmp.replace(/(>[^<>]*)>/g, '$1');
            tmp = tmp.replace(/<([^<>]*<)/g, '$1');

            // 语言修复
            var lan = $('form .i18n-lang').val();
            switch (lan) {
                // 瓜拉尼语
                case 'gn':
                    tmp = tmp.replace(/> rehegua/g, '>');
                    tmp = tmp.replace(/>pe/g, '>');
                    tmp = tmp.replace(/<tabla /g, '<table ');
                    tmp = tmp.replace(/ clase="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)tabla-condensada([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ estilo="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)ancho:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<tete>/g, '<tbody>');
                    tmp = tmp.replace(/<\/mbarete>/g, '</strong>');
                    break;
                // 卢旺达语
                case 'rw':
                    tmp = tmp.replace(/<imbonerahamwe /g, '<table ');
                    tmp = tmp.replace(/ yimeza="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)ameza-yegeranye([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)ubugari:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*)ibara:#([^\"]*)"/g, '="$1color:#$2"');
                    break;
                // 布尔语(南非荷兰语)
                case 'af':
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    break;
                // 约鲁巴语
                case 'yo':
                    tmp = tmp.replace(/<tabili /g, '<table ');
                    tmp = tmp.replace(/="([^\"]*)tabili-condensed([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/<\/tabili>/g, '</table>');
                    tmp = tmp.replace(/<igba>/g, '<span>');
                    break;
                // 贡根语
                case 'gom':
                    tmp = tmp.replace(/> हें नांव/g, '>');
                    tmp = tmp.replace(/> अशें म्हण्टात/g, '>');
                    tmp = tmp.replace(/="([^\"]*)कोष्टक-घनीभूत([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)रुंदी:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ऑटो;([^\"]*)"/g, '="$1:auto;$2"');
                    break;
                // 法语
                case 'fr':
                    tmp = tmp.replace(/<corps>/g, '<tbody>');
                    break;
                // 夏威夷语
                case 'haw':
                    tmp = tmp.replace(/<ke kino>/g, '<tbody>');
                    tmp = tmp.replace(/<\/papa>/g, '</table>');
                    break;
                // 俄语
                case 'ru':
                    tmp = tmp.replace(/<р>/g, '<p>');
                    tmp = tmp.replace(/<тело>/g, '<tbody>');
                    tmp = tmp.replace(/<тр>/g, '<tr>');
                    tmp = tmp.replace(/<тд>/g, '<td>');
                    tmp = tmp.replace(/<\/таблица>/g, '</table>');
                    break;
                // 博杰普尔语
                case 'bho':
                    tmp = tmp.replace(/> के बा/g, '>');
                    tmp = tmp.replace(/="([^\"]*)टेबल-घट्ट([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)चौड़ाई:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ऑटो;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<टीबॉडी>/g, '<tbody>');
                    break;
                // 印地语
                case 'hi':
                    tmp = tmp.replace(/<पी>/g, '<p>');
                    tmp = tmp.replace(/<टेबल /g, '<table ');
                    tmp = tmp.replace(/ क्लास="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)टेबल-कंडेंस्ड([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ शैली="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)चौड़ाई:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ऑटो;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<टीडी>/g, '<td>');
                    tmp = tmp.replace(/<\/तालिका>/g, '</table>');
                    break;
                // 斯瓦希里语
                case 'sw':
                    tmp = tmp.replace(/<\/meza>/g, '</table>');
                    break;
                // 意第绪语
                case 'yi':
                    tmp = tmp.replace(/<טבאָדי>/g, '<tbody>');
                    tmp = tmp.replace(/<טד>/g, '<td>');
                    tmp = tmp.replace(/<\/טיש>/g, '</table>');
                    break;
                // 契维语
                case 'ak':
                    tmp = tmp.replace(/<\/p>, na ɛyɛ/g, '</p>');
                    tmp = tmp.replace(/<\/strong>, na ɛyɛ adwuma wɔ hɔ/g, '</strong>');
                    tmp = tmp.replace(/> na ɛwɔ hɔ/g, '>');
                    tmp = tmp.replace(/> na ɛyɛ/g, '>');
                    tmp = tmp.replace(/="([^\"]*)table-a wɔabɔ no mua([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)trɛw:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<nipadua>/g, '<tbody>');
                    break;
                // 古吉拉特语
                case 'gu':
                    tmp = tmp.replace(/<\/ટેબલ>/g, '</table>');
                    break;
                // 卡纳达语
                case 'kn':
                    tmp = tmp.replace(/<ಟೇಬಲ್ /g, '<table ');
                    tmp = tmp.replace(/ ವರ್ಗ="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)ಟೇಬಲ್-ಕಂಡೆನ್ಸ್ಡ್([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ ಶೈಲಿ="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)ಅಗಲ:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ಸ್ವಯಂ;([^\"]*)"/g, '="$1:auto;$2"');
                    break;
                // 阿拉伯语
                case 'ar':
                    tmp = tmp.replace(/<ص>/g, '<p>');
                    tmp = tmp.replace(/<\/ص>/g, '</p>');
                    tmp = tmp.replace(/<فئة الجدول="الجدول المكثف" نمط="العرض: تلقائي؛">/g, '<table class="table-condensed" style="width:auto;">');
                    tmp = tmp.replace(/<الجسم>/g, '<tbody>');
                    tmp = tmp.replace(/<تر>/g, '<tr>');
                    tmp = tmp.replace(/<TD>/g, '<td>');
                    tmp = tmp.replace(/<\/TD>/g, '</td>');
                    tmp = tmp.replace(/<\/الجدول>/g, '</table>');
                    tmp = tmp.replace(/<\/قوي>/g, '</strong>');
                    break;
                // 孟加拉语
                case 'bn':
                    tmp = tmp.replace(/<\/টেবিল>/g, '</table>');
                    break;
                // 萨摩亚语
                case 'sm':
                    tmp = tmp.replace(/<tino>/g, '<tbody>');
                    tmp = tmp.replace(/<\/laulau>/g, '</table>');
                    break;
                // 印尼巽他语
                case 'su':
                    tmp = tmp.replace(/<sadayana>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    break;
                // 越南语
                case 'vi':
                    tmp = tmp.replace(/<người>/g, '<tbody>');
                    tmp = tmp.replace(/<\/bảng>/g, '</table>');
                    tmp = tmp.replace(/<\/mạnh>/g, '</strong>');
                    break;
                // 马耳他语
                case 'mt':
                    tmp = tmp.replace(/<\/mejda>/g, '</table>');
                    break;
                // 阿萨姆语
                case 'as':
                    tmp = tmp.replace(/<টেবুল /g, '<table ');
                    tmp = tmp.replace(/ শ্ৰেণী="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)টেবুল-ঘনীভূত([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ শৈলী="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)প্ৰস্থ:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):স্বয়ংক্ৰিয়;([^\"]*)"/g, '="$1:auto;$2"');
                    break;
                // 加泰罗尼亚语
                case 'ca':
                    tmp = tmp.replace(/<\/taula>/g, '</table>');
                    break;
                // 僧伽罗语
                case 'si':
                    tmp = tmp.replace(/<\/වගුව>/g, '</table>');
                    break;
                // 宿务语
                case 'ceb':
                    tmp = tmp.replace(/<lawas>/g, '<tbody>');
                    break;
                // 苏格兰盖尔语
                case 'gd':
                    tmp = tmp.replace(/<\/clàr>/g, '</table>');
                    break;
                // 梵语
                case 'sa':
                    tmp = tmp.replace(/<प>/g, '<p>');
                    tmp = tmp.replace(/> इति/g, '>');
                    tmp = tmp.replace(/="([^\"]*)टेसारणी-सघन([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/<तशरीर>/g, '<tbody>');
                    tmp = tmp.replace(/<\/बलिष्ठ>/g, '</strong>');
                    break;
                // 波兰语
                case 'pl':
                    tmp = tmp.replace(/<ciało>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabela>/g, '</table>');
                    break;
                // 加利西亚语
                case 'gl':
                    tmp = tmp.replace(/<\/táboa>/g, '</table>');
                    break;
                // 鞑靼语
                case 'tt':
                    tmp = tmp.replace(/<өстәл /g, '<table ');
                    tmp = tmp.replace(/ классы="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)өстәл конденсацияләнгән([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ стиль="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)киңлек:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):авто;([^\"]*)"/g, '="$1:auto;$2"');
                    break;
                // 日本語
                case 'ja':
                    tmp = tmp.replace(/<本体>/g, '<tbody>');
                    tmp = tmp.replace(/<\/テーブル>/g, '</table>');
                    break;
                // 艾马拉语
                case 'ay':
                    tmp = tmp.replace(/> ukat juk’ampinaka/g, '>');
                    tmp = tmp.replace(/> sasaw sapxi/g, '>');
                    tmp = tmp.replace(/> qillqata/g, '>');
                    tmp = tmp.replace(/> ukax mä juk’a pachanakanwa/g, '>');
                    tmp = tmp.replace(/> ukan uñt’ayata/g, '>');
                    tmp = tmp.replace(/<tabla /g, '<table ');
                    tmp = tmp.replace(/ clase="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)tabla-condensada([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ estilo="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)ancho:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<\/ch’ama>/g, '</strong>');
                    break;
                // 罗马尼亚语
                case 'ro':
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    break;
                // 海地克里奥尔语
                case 'ht':
                    tmp = tmp.replace(/<\/tab>/g, '</table>');
                    break;
                // 多格来语
                case 'doi':
                    tmp = tmp.replace(/<प>/g, '<p>');
                    tmp = tmp.replace(/<पी>/g, '<p>');
                    tmp = tmp.replace(/<\/p>दा ऐ/g, '</p>');
                    tmp = tmp.replace(/> दा/g, '>');
                    tmp = tmp.replace(/ऐ </g, '<');
                    tmp = tmp.replace(/>दा ऐ/g, '>');
                    tmp = tmp.replace(/> ऐ/g, '>');
                    tmp = tmp.replace(/> होग/g, '>');
                    tmp = tmp.replace(/<तालिका /g, '<table ');
                    tmp = tmp.replace(/ वर्ग="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)तालिका-घट्ट([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ शैली="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)चौड़ाई:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ऑटो;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<टीबॉडी>/g, '<tbody>');
                    tmp = tmp.replace(/<टीडी>/g, '<td>');
                    tmp = tmp.replace(/<\/मजबूत>/g, '</strong>');
                    break;
                // 迈蒂利语
                case 'mai':
                    tmp = tmp.replace(/<\/p>क/g, '</p>');
                    tmp = tmp.replace(/> छै/g, '>');
                    tmp = tmp.replace(/>क/g, '>');
                    tmp = tmp.replace(/> अछि/g, '>');
                    tmp = tmp.replace(/> देखू/g, '>');
                    tmp = tmp.replace(/="([^\"]*)तालिका-घनीभूत([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)चौड़ाई:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ऑटो;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<शरीर>/g, '<tbody>');
                    break;
                // 泰语
                case 'th':
                    tmp = tmp.replace(/="([^\"]*)table-ย่อ([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/<\/ตาราง>/g, '</table>');
                    tmp = tmp.replace(/<\/\/แข็งแกร่ง>/g, '</strong>');
                    break;
                // 迪维希语
                case 'dv':
                    tmp = tmp.replace(/> އެވެ/g, '>');
                    break;
                // 卢森堡语
                case 'lb':
                    tmp = tmp.replace(/> dir/g, '>');
                    tmp = tmp.replace(/<\/Dësch>/g, '</table>');
                    break;
                // 信德语
                case 'sd':
                    tmp = tmp.replace(/<\/ٽيبل>/g, '</table>');
                    break;
                // 卢干达语
                case 'lg':
                    tmp = tmp.replace(/="([^\"]*)emmeeza-efunvuddwa([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)obugazi:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<omubiri>/g, '<tbody>');
                    tmp = tmp.replace(/<\/amaanyi>/g, '</strong>');
                    break;
                // 马拉地语
                case 'mr':
                    tmp = tmp.replace(/<\/टेबल>/g, '</table>');
                    break;
                // 葡萄牙语
                case 'pt':
                    tmp = tmp.replace(/<corpo>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabela>/g, '</table>');
                    break;
                // 奥罗莫语
                case 'om':
                    tmp = tmp.replace(/> jechuun ni danda\'ama/g, '>');
                    tmp = tmp.replace(/> jechuun ni danda’ama/g, '>');
                    tmp = tmp.replace(/>n jedhu/g, '>');
                    tmp = tmp.replace(/<gita /g, '<table ');
                    tmp = tmp.replace(/ gabatee="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)gabatee-gabatee([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)bal'ina:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<qaama>/g, '<tbody>');
                    tmp = tmp.replace(/<\/cimaa>/g, '</strong>');
                    break;
                // 西班牙语
                case 'es':
                    tmp = tmp.replace(/="([^\"]*)ancho:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<tcuerpo>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabla>/g, '</table>');
                    tmp = tmp.replace(/<\/fuerte>/g, '</strong>');
                    break;
                // 弗里西语
                case 'fy':
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    break;
                // 阿姆哈拉语
                case 'am':
                    tmp = tmp.replace(/<\/ሠንጠረዥ>/g, '</table>');
                    break;
                // 意大利语
                case 'it':
                    tmp = tmp.replace(/<corpo>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tcorpo>/g, '</tbody>');
                    tmp = tmp.replace(/<\/tabella>/g, '</table>');
                    break;
                // 阿尔巴尼亚语
                case 'sq':
                    tmp = tmp.replace(/<\/tabela>/g, '</table>');
                    break;
                // 韩语
                case 'ko':
                    tmp = tmp.replace(/<테이블 /g, '<table ');
                    tmp = tmp.replace(/ 클래스="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)테이블 압축([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ 스타일="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)너비:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):자동;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<본체>/g, '<tbody>');
                    tmp = tmp.replace(/<TD>/g, '<td>');
                    tmp = tmp.replace(/<\/강하게>/g, '</strong>');
                    break;
                // 塔吉克语
                case 'tg':
                    tmp = tmp.replace(/<тд>/g, '<td>');
                    tmp = tmp.replace(/<\/ҷадвал>/g, '</table>');
                    break;
                // 吉尔吉斯语
                case 'ky':
                    tmp = tmp.replace(/<таблица /g, '<table ');
                    tmp = tmp.replace(/ классы="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)таблица-конденсацияланган([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ стили="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)туурасы:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):авто;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<\/таблица>/g, '</table>');
                    break;
                // 埃维语
                case 'ee':
                    tmp = tmp.replace(/> ƒe nyawo/g, '>');
                    tmp = tmp.replace(/> ƒe nyatakakadzraɖoƒea/g, '>');
                    tmp = tmp.replace(/ atsyã="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)kekeme:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<ŋutilã>/g, '<tbody>');
                    tmp = tmp.replace(/<\/sesẽ>/g, '</strong>');
                    break;
                // 克丘亚语
                case 'qu':
                    tmp = tmp.replace(/> nisqapi/g, '>');
                    tmp = tmp.replace(/> nispa/g, '>');
                    tmp = tmp.replace(/> nisqa/g, '>');
                    tmp = tmp.replace(/<tabla /g, '<table ');
                    tmp = tmp.replace(/ clase="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)tabla-condensada([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ estilo="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)ancho:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<cuerpo>/g, '<tbody>');
                    break;
                // 毛利语
                case 'mi':
                    tmp = tmp.replace(/="([^\"]*)whanui:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<te tinana>/g, '<tbody>');
                    break;
                // 蒂格尼亚语
                case 'ti':
                    tmp = tmp.replace(/> ዝብል ጽሑፍ ኣሎ።/g, '>');
                    tmp = tmp.replace(/="([^\"]*)ሰንጠረዥ-ዝተሓጽረ([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)ስፍሓት:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ኣውቶ;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<ኣካል>/g, '<tbody>');
                    break;
                // 哈萨克语
                case 'kk':
                    tmp = tmp.replace(/<кесте /g, '<table ');
                    tmp = tmp.replace(/ классы="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)кесте-конденсацияланған([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/<\/кесте>/g, '</table>');
                    break;
                // 荷兰语
                case 'nl':
                    tmp = tmp.replace(/<tlichaam>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tlichaam>/g, '</tbody>');
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    tmp = tmp.replace(/<\/sterk>/g, '</strong>');
                    break;
                // 克里奥尔语
                case 'kri':
                    tmp = tmp.replace(/> we de na di wɔl/g, '>');
                    tmp = tmp.replace(/> we dɛn kɔl/g, '>');
                    tmp = tmp.replace(/>, we yu de yuz/g, '>');
                    tmp = tmp.replace(/<tebul /g, '<table ');
                    tmp = tmp.replace(/ klas="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)tebul-kɔndɛns([^\"]*)"/g, '="$1table-condensed$2"');
                    tmp = tmp.replace(/ stayl="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)wid:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ɔto;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<tbɔdi>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tebul>/g, '</table>');
                    break;
                // 林格拉语
                case 'ln':
                    tmp = tmp.replace(/<\/p>, oyo ezali/g, '</p>');
                    tmp = tmp.replace(/> na yango/g, '>');
                    tmp = tmp.replace(/="([^\"]*)tebul-kɔndɛns([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)largeur:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<nzoto>/g, '<tbody>');
                    tmp = tmp.replace(/<\/makasi>/g, '</strong>');
                    break;
                // 蒙古语
                case 'mn':
                    tmp = tmp.replace(/<хүснэгт /g, '<table ');
                    tmp = tmp.replace(/ анги="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)хүснэгт-condensed([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/<\/хүснэгт>/g, '</table>');
                    break;
                // 米佐语
                case 'lus':
                    tmp = tmp.replace(/> ah hian kan hmu a/g, '>');
                    tmp = tmp.replace(/> tih a ni/g, '>');
                    tmp = tmp.replace(/> tih hi a ni/g, '>');
                    tmp = tmp.replace(/> a ni a/g, '>');
                    tmp = tmp.replace(/> a ni/g, '>');
                    tmp = tmp.replace(/>ng/g, '>');
                    tmp = tmp.replace(/="([^\"]*)a zau zawng:([^\"]*)"/g, '="$1width:$2"');
                    break;
                // 南非科萨语
                case 'xh':
                    tmp = tmp.replace(/<\/umzimba>/g, '</tbody>');
                    break;
                // 南非祖鲁语
                case 'zu':
                    tmp = tmp.replace(/<\/ithebula>/g, '</table>');
                    break;
                // 塞尔维亚语
                case 'sr':
                    tmp = tmp.replace(/<п>/g, '<p>');
                    tmp = tmp.replace(/<\/п>/g, '</p>');
                    tmp = tmp.replace(/<стронг>/g, '<strong>');
                    tmp = tmp.replace(/<\/стронг>/g, '</strong>');
                    tmp = tmp.replace(/<спан>/g, '<span>');
                    tmp = tmp.replace(/<спан стиле=/g, '<span style=');
                    tmp = tmp.replace(/<\/спан\s*>/g, '</span>');
                    tmp = tmp.replace(/"цолор:/g, '"color:');
                    tmp = tmp.replace(/(#[^#;"ф]*)фф([^#;"ф]*;")/g, '$1ff$2');
                    tmp = tmp.replace(/<бр \/>/g, '<br />');
                    tmp = tmp.replace(/<имг /g, '<img ');
                    tmp = tmp.replace(/<табле /g, '<table ');
                    tmp = tmp.replace(/ цласс="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)табле-цонденсед([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/ стиле="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)видтх:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/="([^\"]*):ауто;([^\"]*)"/g, '="$1:auto;$2"');
                    tmp = tmp.replace(/<тбоди>/g, '<tbody>');
                    tmp = tmp.replace(/<тр>/g, '<tr>');
                    tmp = tmp.replace(/<тд>/g, '<td>');
                    tmp = tmp.replace(/<\/тд>/g, '</td>');
                    tmp = tmp.replace(/<\/тр>/g, '</tr>');
                    tmp = tmp.replace(/<\/тбоди>/g, '</tbody>');
                    tmp = tmp.replace(/<\/табле>/g, '</table>');
                    break;
                // 塞佩蒂语
                case 'nso':
                    tmp = tmp.replace(/="([^\"]*)tafola-e khutsofaditšwego([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)bophara:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<mmele>/g, '<tbody>');
                    tmp = tmp.replace(/<\/matla>/g, '</strong>');
                    break;
                // 塞索托语
                case 'st':
                    tmp = tmp.replace(/<botho>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tafole>/g, '</table>');
                    break;
                // 世界语
                case 'eo':
                    tmp = tmp.replace(/<tkorpo>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tablo>/g, '</table>');
                    break;
                // 梅泰语（曼尼普尔语）
                case 'mni-Mtei':
                    tmp = tmp.replace(/>ꯗꯥ ꯐꯣꯉꯗꯣꯛꯂꯤ꯫/g, '>');
                    tmp = tmp.replace(/> ꯍꯥꯌꯅꯥ ꯀꯧꯏ꯫/g, '>');
                    tmp = tmp.replace(/> ꯍꯥꯌꯕꯁꯤꯅꯤ꯫/g, '>');
                    tmp = tmp.replace(/>꯫/g, '>');
                    tmp = tmp.replace(/="([^\"]*)ꯇꯦꯕꯜ-ꯀꯟꯗꯦꯟꯁ ꯇꯧꯕꯥ([^\"]*)"/g, '="$1tableau-condensed$2"');
                    break;
                // 乌兹别克语
                case 'uz':
                    tmp = tmp.replace(/<\/jadval>/g, '</table>');
                    break;
                // 伊洛卡诺语
                case 'ilo':
                    tmp = tmp.replace(/<klase /g, '<table ');
                    tmp = tmp.replace(/ ti lamisaan="/g, ' class="');
                    tmp = tmp.replace(/="([^\"]*)napagtitipon-ti-lamisaan([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/ estilo="/g, ' style="');
                    tmp = tmp.replace(/="([^\"]*)kalawa:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<ti bagi>/g, '<tbody>');
                    tmp = tmp.replace(/<\/napigsa>/g, '</strong>');
                    break;
                // 印尼语
                case 'id':
                    tmp = tmp.replace(/<tubuh>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    tmp = tmp.replace(/<\/kuat>/g, '</strong>');
                    break;
                // 印尼爪哇语
                case 'jw':
                    tmp = tmp.replace(/<tiyang>/g, '<tbody>');
                    tmp = tmp.replace(/<\/tabel>/g, '</table>');
                    break;
                // 宗加语
                case 'ts':
                    tmp = tmp.replace(/="([^\"]*)tafula-ri hlanganisiwile([^\"]*)"/g, '="$1tableau-condensed$2"');
                    tmp = tmp.replace(/="([^\"]*)ku anama:([^\"]*)"/g, '="$1width:$2"');
                    tmp = tmp.replace(/<miri>/g, '<tbody>');
                    break;
                default:
                // Nothing to do
            }

            // 标签修复
            tmp = tmp.replace(/([\?;"]) br\s*\/>/gi, '$1<br />');
            tmp = tmp.replace(/<[^>]*br\s*\/>/gi, '<br />');
            tmp = tmp.replace(/<[^>]*br\s*>/gi, '<br />');
            tmp = tmp.replace(/<br[^>]*>/gi, '<br />');
            tmp = tmp.replace(/ br \/>/gi, '<br />');
            tmp = tmp.replace(/<[^>]*\/[^>]*span[^>]*>/gi, '</span>');
            tmp = tmp.replace(/(<strong>[^<\/]*)\/strong>/gi, '$1</strong>');
            tmp = tmp.replace(/(<span[^>]*>[^<\/]*)\/span>/gi, '$1</span>');
            tmp = tmp.replace(/(<strong>[^<>]*) strong>/gi, '$1</strong>');
            tmp = tmp.replace(/(<span[^>]*>[^<>]*) span>/gi, '$1</span>');
            tmp = tmp.replace(/(<p[^>]*>\s*<strong>[^<>]*)(<\/p>)/gi, '$1</strong>$2');
            tmp = tmp.replace(/(<p[^>]*>\s*<span[^>]*>[^<>]*)(<\/p>)/gi, '$1</span>$2');
            tmp = tmp.replace(/(<strong[^>]*>\s*<span[^>]*>[^<>]*)(<\/strong>)/gi, '$1</span>$2');
            tmp = tmp.replace(/(<span[^>]*>\s*<strong[^>]*>[^<>]*)(<\/span>)/gi, '$1</strong>$2');
            tmp = tmp.replace(/<span>(<strong>[^<>]*<\/strong>)<\/span>/gi, '$1');
            tmp = tmp.replace(/(<strong>[^<>]*)<\/strong>\s*<strong>([^<>]*<\/strong>)/gi, '$1$2');
            tmp = tmp.replace(/<strong>\s*<\/strong>/gi, ' ');
            tmp = tmp.replace(/(<strong>)\s*<br \/>/gi, '$1');
            tmp = tmp.replace(/<br \/>\s*(<\/strong>)/gi, '$1');
            tmp = tmp.replace(/<span>([^<>]*)<\/span>/gi, '$1');
            tmp = tmp.replace(/<span[^>]*>\s*<\/span>/gi, ' ');
            tmp = tmp.replace(/(<span[^>]*>)([^<>]*)(<span[^>]*>[^<>]*<\/span>)([^<>]*)(<\/span>)/gi, '$1$2</span>$3$1$4$5');
            tmp = tmp.replace(/(<span style="[^\"']*)font-size:12px;([^\"']*">)/gi, '$1$2');
            tmp = tmp.replace(/(<span style="[^\"']*)font-size:14px;([^\"']*">)/gi, '$1$2');
            tmp = tmp.replace(/(<span style="[^\"']*)font-size:16px;([^\"']*">)/gi, '$1$2');
            tmp = tmp.replace(/<span style="\s*">(<strong>[^<>]*<\/strong>)<\/span>/gi, '$1');
            tmp = tmp.replace(/<span style="\s*">([^<>]*)<\/span>/gi, '$1');
            tmp = tmp.replace(/<p[^>]*>\s*<\/p>/gi, ' ');
            tmp = tmp.replace(/<[\/]*s>/gi, ' ');

            // 图片替换
            var ori = '';
            if (typeof window.editor_1 !== 'undefined') {
                var ori = window.editor_1.html();
            }
            if (ori && !tmp) {
                return layer.msg('Content is empty!', { icon: 3 });
            }
            var imgs = ori.match(/<img[^>]*>/gi);
            var reps = tmp.match(/<img[^>]*>/gi);
            if (imgs && imgs.length) {
                if (!reps || imgs.length !== reps.length) {
                    return layer.msg('Image length error!', { icon: 3 })
                } else {
                    for (var i = 0; i < imgs.length; i++) {
                        tmp = tmp.replace(new RegExp(reps[i], 'gi'), imgs[i]);
                    }
                }
            }

            // 替换校验
            if (typeof window.editor1 !== 'undefined') {
                window.editor1.html(tmp);
            }
            var err = chk_err();
            $('#chk-res').html(err.join(' | '));

            // 分配替换规则
            if ($('#orig').length && $('#repl').length) {
                $('#orig').val('');
                $('#repl').val('');
                if (err.length) {
                    var check = err.shift().match(/(strong|span)-(\d+)/i);
                    if (check) {
                        var arr = [
                            { reg: '<' + check[1] + '[^>]*>([^<>]*<\\/p>)', rep: '$1' },
                            { reg: '(<p>[^<>]*)<\\/' + check[1] + '>', rep: '$1' },
                            { reg: '<' + check[1] + '[^>]*>([^<>]*<' + check[1] + '[^>]*>)', rep: '$1' },
                            { reg: '(<\\/' + check[1] + '>[^<>]*)<\\/' + check[1] + '>', rep: '$1' },
                            { reg: ' (:#[A-Za-z0-9]{6};)([^"<>]*)">', rep: ' <' + check[1] + ' style="color:$1$2">' },
                        ];
                        for (var i = 0; i < arr.length; i++) {
                            if (tmp.match(new RegExp(arr[i].reg))) {
                                $('#orig').val(arr[i].reg);
                                $('#repl').val(arr[i].rep);
                                break;
                            }
                        }
                    }
                }
            }
        }
        $('form #rep-err').click(rep_err);

        // 临时翻译编辑器批量替换
        $('form #res-rep').click(function () {
            var orig = new RegExp($('#orig').val(), 'gi');
            var repl = $('#repl').val();
            if (!$('#orig').val().length) return layer.msg('Find string is empty!');
            var tmp = window.editor1.html();
            tmp = tmp.replace(orig, repl);
            window.editor1.html(tmp);
            $('#orig').val('');
            $('#repl').val('');
            rep_err();
        });

        // 临时翻译写入数据库
        $('form #write-db').click(function () {
            if ($('#chk-res').length) {
                var err = chk_err();
                if (err.length) {
                    $('#chk-res').html(err.join(' | '));
                    return layer.alert('Please repair: ' + err.join(' | '), { icon: 2 });
                }
                $('#chk-res').html('');
                $('#orig').length && $('#orig').val('');
                $('#repl').length && $('#repl').val('');
            }
            $('.ke-container .ke-toolbar .ke-outline.ke-selected .ke-icon-source').length && $('.ke-container .ke-toolbar .ke-outline.ke-selected .ke-icon-source').click();
            setTimeout(function () {
                $('button[lay-filter="submit"]').trigger('click');
            }, 1000);
        });

        // 临时翻译自动写入数据库
        if ($('input[lay-filter="auto-db"]').length) {
            form.on('checkbox(auto-db)', function (data) {
                if (data.elem.checked) {
                    localStorage.setItem('autoWriteDb', 1);
                } else {
                    localStorage.setItem('autoWriteDb', 0);
                }
            });
            if (localStorage.getItem('autoWriteDb') == 1) {
                $('form input[lay-filter="auto-db"]').prop('checked', true);
                form.render('checkbox');
                auto_write_db();
            } else {
                $('form input[lay-filter="auto-db"]').prop('checked', false);
                form.render('checkbox');
            }
        }
        function auto_write_db() {
            var tlang = $('select[name="lang"]').val();
            if (!tlang) return false;
            var curr = $('select[name="lang"]').children('option[value="' + tlang + '"]');
            if (tlang == 'ts' && curr.text().slice(-1) == '√' && curr.prev().val() && curr.prev().text().slice(-1) == '√') {
                var pos = location.href.lastIndexOf('/');
                var aid = parseInt(location.href.slice(pos + 1).split('.')[0]) + 1;
                location.href = location.href.slice(0, pos) + '/' + aid + '.html?tlang=gn';
                return layer.msg('Auto translate have done!', { icon: 1 });
            }
            // 判断上下文
            if (curr.text().slice(-1) == '√' && ((curr.prev().val() && curr.prev().text().slice(-1) == '√') || curr.prev().val() == 'zh-TW' || curr.next().val() == 'zh-CN') && (curr.next().text().slice(-1) != '√' || curr.next().val() == 'zh-CN')) {
                curr.next().val() && setTimeout(function () {
                    if (curr.next().val() == 'zh-TW' || curr.next().val() == 'zh-CN') {
                        location.href = location.href.replace('?tlang=' + tlang, '?tlang=' + curr.next().next().val());
                    } else {
                        location.href = location.href.replace('?tlang=' + tlang, '?tlang=' + curr.next().val());
                    }
                }, 1000);
            } else if (curr.text().slice(-1) != '√' && ((curr.prev().val() && curr.prev().text().slice(-1) == '√') || curr.prev().val() == 'zh-TW')) {
                $('#chk-loading').removeClass('layui-hide');
                setTimeout(function () {
                    $('#chk-loading').addClass('layui-hide');
                    $('form .fill-translate').trigger('click');
                    // 开始轮询
                    var n = 0;
                    var write = setInterval(function () {
                        n++;
                        if ((write && (($('form input[name="name"]').length && $('form input[name="name"]').val()) || ($('form input[name="title"]').length && $('form input[name="title"]').val()))) || n >= 30) {
                            clearInterval(write);
                            write = null;
                            if (n < 30 && (($('form input[name="name"]').length && $('form input[name="name"]').val()) || ($('form input[name="title"]').length && $('form input[name="title"]').val()))) {
                                $('form #rep-err').trigger('click');
                                var err = chk_err();
                                if (err.indexOf('Category') === -1 && err.indexOf('Tag') === -1) {
                                    setTimeout(function () {
                                        $('form #write-db').trigger('click');
                                    }, 1000);
                                } else {
                                    // 修复翻译分类
                                    if (err.indexOf('Category') !== -1) {
                                        var obj = $('select[name="_category_id"]');
                                        var tbj = $('select[name="category_id"]');
                                        if (obj.length && tbj.length && tbj.siblings('div.layui-form-select').length) {
                                            var selectIndex = obj.children('option:selected').index();
                                            var selectCid = tbj.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).attr('lay-value');
                                            var selectVal = tbj.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).attr('data-tran');
                                            if (selectIndex && selectCid && selectVal) {
                                                $.ajax({
                                                    url: site_url + '/' + lang + '/' + module + '/' + controller + '/save_category.html',
                                                    type: 'post',
                                                    dataType: 'json',
                                                    data: { cid: selectCid, cat: selectVal },
                                                    success: function (res) {
                                                        if (res.code) return layer.alert(res.msg, { icon: 2 });
                                                        tbj.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).removeAttr('data-tran').trigger('click');
                                                        layer.msg(res.msg);
                                                        if (err.indexOf('Tag') === -1) {
                                                            $('form #write-db').trigger('click');
                                                        } else {
                                                            location.reload();
                                                        }
                                                    },
                                                    error: function (XMLHttpRequest, textStatus) {
                                                        layer.alert(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                                                    },
                                                });
                                            } else {
                                                return layer.alert('Category not match!', { icon: 2 });
                                            }
                                        }
                                    }
                                    // 修复翻译标签
                                    if (err.indexOf('Tag') !== -1) {
                                        var obj = $('input[name="_tag_ids[]"]');
                                        var tbj = $('input[name="tag_ids[]"]');
                                        if (obj.length && tbj.length && obj.length === tbj.length && $('input[name="tags"]').val()) {
                                            var tags = $('input[name="tags"]').val().replace(/(\d)\,(\d)/g, '$1$2').split(',');
                                            var tids = [];
                                            for (var i = 0; i < obj.length; i++) {
                                                if ($(obj[i]).prop('checked')) {
                                                    if (!$(tbj[i]).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                                        tids.push($(tbj[i]).val());
                                                        $(tbj[i]).next('div.layui-form-checkbox').trigger('click');
                                                    }
                                                }
                                            }
                                            if (tids.length === tags.length) {
                                                $.ajax({
                                                    url: site_url + '/' + lang + '/' + module + '/' + controller + '/save_tag.html',
                                                    type: 'post',
                                                    dataType: 'json',
                                                    data: { tids: tids, tags: tags },
                                                    success: function (res) {
                                                        if (res.code) return layer.alert(res.msg, { icon: 2 });
                                                        $('input[name="tags"]').val('');
                                                        layer.msg(res.msg);
                                                        if (err.indexOf('Category') === -1) {
                                                            $('form #write-db').trigger('click');
                                                        } else {
                                                            location.reload();
                                                        }
                                                    },
                                                    error: function (XMLHttpRequest, textStatus) {
                                                        layer.alert(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                                                    },
                                                });
                                            } else {
                                                return layer.alert('Tags not match!', { icon: 2 });
                                            }
                                        }
                                    }
                                }
                            } else {
                                layer.alert('Request time out!', { icon: 2 });
                            }
                        }
                    }, 2000);
                }, 10000 + Math.ceil(Math.random() * 20000));
            }
        }

        // 临时翻译方便返回顶部
        util.fixbar({
            top: true,
            css: { right: 15, bottom: 35 },
            bgcolor: '#16889aa',
            click: function (type) { }
        });

        var site_url = '//{$smarty.server.SERVER_NAME}' + (('{$smarty.server.SERVER_PORT}' == '80' || '{$smarty.server.SERVER_PORT}' == '443') ? '' : ':{$smarty.server.SERVER_PORT}');
        var path_info = '{$smarty.server.REQUEST_URI|modifier:htmlentities}'.split('?')[0].split('/');
        var timer = null;
        // var translate_api = 'https://translate.googleapis.com/translate_a/single';
        var translate_api = site_url.match(/localhost|127.0.0.1/i) ? 'https://yesu.co/api/translate' : site_url + '/api/translate';
        var suggest_api = 'https://www.google.com/complete/search';
        suggest_api = site_url.match(/localhost|127.0.0.1/i) ? 'https://yesu.co/api/fetch?method=get&url=' + suggest_api : site_url + '/api/fetch?method=get&url=' + suggest_api;

        // 获取应用、控制器和方法
        var lang = path_info[1],
            module = path_info[2].toLocaleLowerCase(),
            controller = path_info[3].toLocaleLowerCase(),
            action = path_info[4].split('.')[0].toLocaleLowerCase();

        // 如果非框架内
        if (self.frameElement && self.frameElement.tagName == 'IFRAME' && action !== 'index') {
            if (parent.layer.getFrameIndex(window.name))
                $('form.layui-form .layui-elem-field').remove();
            else
                !$('form.layui-form .layui-elem-field').length && $('form.layui-form').prepend('<fieldset class="layui-elem-field layui-field-title"><legend>' + (action == 'create' ? '添加' : (action == 'edit' ? '编辑' : '信息')) + '</legend></fieldset>');
        }

        // 日期
        $('form .date').each(function () {
            laydate.render({
                elem: 'input[name="' + $(this).attr('name') + '"]',
                type: $(this).data('type') || 'date'
            });
        });

        // 颜色
        $('form .color').each(function () {
            var input_id = $(this).attr('name');
            $(this).parent().parent().append('<div class="layui-inline" style="left: -11px;"><div id="' + input_id + '-render"></div></div>');
            colorpicker.render({
                elem: '#' + input_id + '-render',
                done: function (color) {
                    $('input[name="' + input_id + '"]').val(color);
                }
            });
        });

        // 上传
        $('form .upload').each(function () {
            var input_id = $(this).attr('name');
            $(this).parent().append('<div class="layui-upload-list" style="position:relative;"></div>');
            $(this).parent().parent().append('<button type="button" class="layui-btn layui-btn-primary" id="' + input_id + '-render"><i class="layui-icon layui-icon-upload"></i> {$localize.upload}</button>');
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            }
            upload.render({
                elem: '#' + input_id + '-render',
                url: site_url + '/' + lang + '/' + module + '/media/upload.html',
                data: {},
                before: function () {
                    layer.load();
                },
                done: function (res, index, upload) {
                    layer.closeAll('loading');
                    if (res.code > 0) return layer.msg(res.msg, { icon: 2 });
                    //上传成功
                    $(this.item).prev().find('input[name="' + input_id + '"]').val(res.data.src)
                    if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test(res.data.src)) {
                        $(this.item).prev().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + res.data.src + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
                    }
                },
                error: function (index, upload) {
                    layer.closeAll('loading');
                }
            });
        });
        $('form .upload').change(function () {
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            } else {
                $(this).parent().find('.layui-upload-list').html(null);
            }
        });
        $('form .layui-upload-list').on('click', '.layui-icon-close-fill', function () {
            $(this).parent().prev().val(null);
            $(this).parent().html(null);
        });

        // layedit富文本
        var editors = [];
        layedit.set({
            uploadImage: {
                url: site_url + '/' + lang + '/' + module + '/media/upload.html', //接口url
                type: 'post', //默认post
            }
        });
        $('form .editor').each(function () {
            var editor_id = $(this).attr('name');
            $(this).attr('id', editor_id);
            $(this).attr('lay-verify', editor_id);
            editors[editor_id] = layedit.build(editor_id, {
                tool: [
                    'strong', //加粗
                    'italic', //斜体
                    'underline', //下划线
                    'del', //删除线
                    '|', //分割线
                    'left', //左对齐
                    'center', //居中对齐
                    'right', //右对齐
                    '|', //分割线
                    'link', //超链接
                    'unlink', //清除链接
                    'face', //表情
                    'image', //插入图片
                ]
            });
        });

        // 监听提交
        form.on('submit(submit)', function (data) {
            if ('undefined' !== typeof KindEditor && window.editor1) {
                if (window.editor1.isEmpty() && (controller !== 'page' || (controller === 'i18n' && action !== 'page-i18n'))) {
                    window.editor1.focus();
                    return layer.msg('{$localize.editor_empty}', { icon: 2 });
                }
                data.field.content = window.editor1.html();
                // 临时翻译校验
                if ($('#chk-res').length) {
                    var err = chk_err();
                    if (err.length) {
                        return layer.alert('Translate need repair: ' + err.join(' | '), { icon: 2 });
                    }
                }
            }
            for (var editor in editors) {
                data.field[editor] = layedit.getContent(editors[editor]);
            }
            $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/' + (action == 'edit' ? 'update' : 'save' + (action == 'create' ? '' : '_' + action)) + '.html', data.field, function (res) {
                if (res.code) return layer.alert(res.msg, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] });
                layer.alert(res.msg, { title: '{$localize.info}', icon: 1, btn: ['{$localize.ok}'] });
                setTimeout(function () {
                    var _ta = window, parentIndex = parent.layer.getFrameIndex(window.name);
                    if (typeof parentIndex !== 'undefined') {
                        parent.layer.close(parentIndex);
                        _ta = parent.window;
                    }
                    if (typeof _ta.layui.table !== 'undefined' && _ta.layui.table.index == 1 && _ta.render && _ta.render.elem) {
                        _ta.layui.table.reload(_ta.render.elem.replace(/#/, ''));
                    } else if (typeof res.url !== 'undefined' && res.url) {
                        _ta.location.href = res.url;
                    } else {
                        _ta.location.reload();
                    }
                }, 1000);
            }, 'json');
            return false;
        });

        // 语言国际化
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').on('blur input', function (e) {
            if (timer) return false;
            timer = setTimeout(function () {
                var str = $.trim($(e.target).val());
                var n = str.split("\n").length;
                var s = '';
                for (var i = 1; i <= n; i++) {
                    s += i + "\n";
                }
                $(e.target).parent().prev().find('textarea[disabled="disabled"]').val(s);
                $(e.target).next('.layui-word-aux').text('{$localize.lines}' + ' ' + n);
                clearTimeout(timer);
                timer = null;
            }, 100);
        });
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').resize(function (e) {
            if (timer) return false;
            timer = setTimeout(function () {
                $(e.target).parent().prev().find('textarea[disabled="disabled"]').height($(e.target).height());
                clearTimeout(timer);
                timer = null;
            }, 100);
        });
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').scroll(function (e) {
            $(this).parent().prev().find('textarea[disabled="disabled"]').scrollTop($(this).scrollTop());
        });

        // 语言框改变
        form.on('select(i18nsltl)', function (data) {
            var st = $(data.elem).attr('name');
            var voice = $(data.elem).children('option:selected').data('voice');
            if (voice) {
                $('form.i18n .speak-' + st + '-voice').children('button').removeClass('layui-btn-disabled').attr('disabled', false);
            } else {
                $('form.i18n .speak-' + st + '-voice').children('button').addClass('layui-btn-disabled').attr('disabled', true);
            }
        });

        // 生成语言包
        form.on('submit(generate)', function (data) {
            $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/generate.html', data.field, function (res) {
                if (res.code) {
                    if (res.code === 2 && res.line) {
                        $('button[lay-active="pos_empty_line"]').trigger('click');
                    }
                    return layer.msg(res.msg, { icon: 2 });
                }
                layer.alert(res.msg, { title: '{$localize.info}', icon: 1, btn: ['{$localize.ok}'] }, function (index) {
                    layer.close(index);
                });
            }, 'json');
            return false;
        });

        // 国际化语言框跳转
        form.on('select(i18nlang)', function (data) {
            var id = $(data.elem).data('id');
            var tlang = $(data.elem).children('option:selected').val();
            var url = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action + '/' + id + '.html?tlang=' + tlang;
            location.href = url;
        });

        // 工具事件
        util.event('lay-active', {
            // 谷歌翻译
            googleTranslate: function (othis) {
                var q = $.trim($('form.i18n textarea[name="q"]').val());
                if (q.length === 0) return $('form.i18n textarea[name="q"]').focus();
                var loading = layer.load(2);
                $.ajax({
                    url: translate_api,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        client: 'gtx',
                        dt: 't',
                        dj: 1,
                        ie: 'UTF-8',
                        oe: 'UTF-8',
                        sl: $('form.i18n select[name="sl"]').val(),
                        tl: $('form.i18n select[name="tl"]').val(),
                        q: q,
                        tk: getTk(q),
                    },
                    success: function (res) {
                        layer.close(loading);
                        if (res && res.sentences) {
                            var str = $.map(res.sentences, function (el) {
                                return el.trans;
                            }).join("");
                            $('form.i18n textarea[name="to"]').val(str);
                            $('form.i18n textarea[name="to"]').next('.layui-word-aux').text('{$localize.lines}' + ' ' + str.split("\n").length);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        layer.close(loading);
                        layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                    },
                });
            },

            // 提取语言包
            fetch: function (othis) {
                var loading = layer.load(2);
                $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/fetch.html', {
                    tl: $('form.i18n select[name="tl"]').val()
                }, function (res) {
                    layer.close(loading);
                    if (res.code) return layer.alert(res.msg, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] }, function (index) {
                        layer.close(index);
                    });
                    var n = res.data.split("\n").length;
                    var m = res.todata.split("\n").length;
                    var ni = '';
                    for (var i = 1; i <= n; i++) {
                        ni += i + "\n";
                    }
                    var mi = '';
                    for (var i = 1; i <= m; i++) {
                        mi += i + "\n";
                    }
                    $('form.i18n textarea[name="q"]').val(res.data);
                    $('form.i18n textarea[name="q"]').parent().prev().find('textarea[disabled="disabled"]').val(ni);
                    $('form.i18n textarea[name="q"]').next('.layui-word-aux').text('{$localize.lines}' + ' ' + n);
                    $('form.i18n textarea[name="to"]').val(res.todata);
                    $('form.i18n textarea[name="to"]').parent().prev().find('textarea[disabled="disabled"]').val(mi);
                    $('form.i18n textarea[name="to"]').next('.layui-word-aux').text('{$localize.lines}' + ' ' + m);
                }, 'json');
            },

            // 划词翻译
            select_tran: function (othis) {
                var q = $('form.i18n input[id="i18n-source"]').val();
                $('form.i18n input[id="i18n-target"]').val('');
                if (q.length === 0) return $('form.i18n input[id="i18n-source"]').focus();
                var loading = layer.load(2);
                $.ajax({
                    url: translate_api,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        client: 'gtx',
                        dt: 't',
                        dj: 1,
                        ie: 'UTF-8',
                        oe: 'UTF-8',
                        sl: $('form.i18n select[name="sl"]').val(),
                        tl: $('form.i18n select[name="tl"]').val(),
                        q: q,
                        tk: getTk(q),
                    },
                    success: function (res) {
                        layer.close(loading);
                        if (res && res.sentences) {
                            var str = $.map(res.sentences, function (el) {
                                return el.trans;
                            }).join("");
                            $('form.i18n input[id="i18n-target"]').val(str);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        layer.close(loading);
                        layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                    },
                });
            },

            // 填充空行
            select_fill: function (othis) {
                var q = $('form.i18n input[id="i18n-source"]').val();
                if (q.length === 0) return $('form.i18n input[id="i18n-source"]').focus();
                var qArr = $('form.i18n textarea[name="q"]').val().split("\n");
                var qIndex = qArr.indexOf(q);
                if (qIndex == -1) return layer.msg('{$localize.select_err}', { icon: 2 });
                var toArr = $('form.i18n textarea[name="to"]').val().split("\n");
                var t = toArr[qIndex];
                if (t == undefined || t.length > 0) return layer.msg('{$localize.select_line_err}', { icon: 2 });
                var loading = layer.load(2);
                $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/fetch.html', {
                    tl: $('form.i18n select[name="tl"]').val()
                }, function (res) {
                    layer.close(loading);
                    if (res.code) return layer.msg(res.msg, { icon: 2 });
                    if ($('form.i18n textarea[name="q"]').val() !== res.data) return layer.msg('{$localize.source_data_changed}', { icon: 2 });
                    toArr[qIndex] = $('form.i18n input[id="i18n-target"]').val();
                    $('form.i18n textarea[name="to"]').val(toArr.join("\n"));
                    var str = toArr.slice(0, qIndex).join("\n");
                    setSelectedText($('form.i18n textarea[name="to"]')[0], str.length + (qIndex ? 1 : 0), str.length + toArr[qIndex].length + (qIndex ? 1 : 0));
                    layer.msg('{$localize.fill_success}' + ' ' + (qIndex + 1), { icon: 1 });
                }, 'json');
            },

            // 定位空行
            pos_empty_line: function (othis) {
                var q = $('form.i18n textarea[name="q"]').val();
                var to = $('form.i18n textarea[name="to"]').val();
                if (q.length <= 0) return layer.msg('{$localize.fetch_source_data}', { icon: 2 });
                var qArr = q.split("\n");
                var toArr = to.split("\n");
                for (var i = 0; i < qArr.length; i++) {
                    if (!toArr[i]) {
                        var strollTo = $('form.i18n textarea[name="q"]')[0].scrollHeight;
                        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').stop().animate({
                            scrollTop: Math.max(strollTo * i / (qArr.length - 1) - 61.8, 0)
                        });
                        var str = qArr.slice(0, i).join("\n");
                        setSelectedText($('form.i18n textarea[name="q"]')[0], str.length + (i ? 1 : 0), str.length + qArr[i].length + (i ? 1 : 0));
                        $('form.i18n input[id="i18n-source"]').val(qArr[i]);
                        $('form.i18n button[lay-active="select_tran"]').trigger('click');
                        return false;
                    }
                }
                return layer.msg('{$localize.fetch_no_empty_line}');
            },

            // 行工具国际化跳转
            i18n_jump: function (othis) {
                if (!othis.data('row-slug')) return layer.msg('{$localize.i18n_slug_empty}', { icon: 2 });
                var _ta = window, parentIndex = parent.layer.getFrameIndex(window.name);
                if (typeof parentIndex !== 'undefined') {
                    parent.layer.close(parentIndex);
                    _ta = parent.window;
                }
                _ta.location.href = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action + '/' + othis.data('id') + '.html?tlang=' + othis.data('slug');
            },

            // 国际化表单返回
            i18n_back: function (othis) {
                location.href = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action + '.html';
            },
        });

        // 语音朗读
        var stopped = true;
        var audio = null;
        var audioArray = [];
        var textArray = [];
        var ttsArr = [];
        var ttsName = '';
        var playErrors = 0;
        var playErrorTimer = null;
        $('form.i18n .speak-voice').on('click', '.layui-icon-speaker', playStartHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-mute', playStopHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-play', playContinueHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-pause', playPauseHander);

        // 播放开始
        function playStartHander() {
            var obj = $(this).parent().parent().find('textarea[name]'), nodes = [];
            audio = new Audio();
            audioArray = [];
            textArray = [];
            ttsArr = obj.val().split("\n");
            ttsName = obj.attr('name');
            for (var i = 0; i < ttsArr.length; i++) {
                if ($.trim(ttsArr[i]) !== '') {
                    nodes.push({ node: ttsArr[i], index: i });
                }
            }
            if (nodes.length < 1) {
                $('textarea[name="' + ttsName + '"]').focus();
                return layer.msg('{$localize.no_voice_text}');
            }
            var voice = '';
            var slug = 'auto';
            if (ttsName == 'q') {
                voice = $('form.i18n select[name="sl"] option:selected').data('voice');
                slug = $('form.i18n select[name="sl"] option:selected').val();
            } else if (ttsName == 'to') {
                voice = $('form.i18n select[name="tl"] option:selected').data('voice');
                slug = $('form.i18n select[name="tl"] option:selected').val();
            }
            if (slug == 'auto') return layer.msg('{$localize.select_voice_lang}');
            if (voice == '') return layer.msg('{$localize.no_voice_support}');
            $(this).addClass('layui-icon-mute').removeClass('layui-icon-speaker layui-btn-primary');
            $(this).parent().append('<button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-icon layui-icon-pause"></button>');
            $('<meta name="referrer" content="same-origin">').appendTo('head').remove();
            var api = 'https://translate.google.com/translate_tts?client=gtx&ie=UTF-8&oe=UTF-8&tl=' + voice + '&q=';
            if (stopped) {
                var num = 200;
                for (var i = 0; i < nodes.length; i++) {
                    var arrs = nodes[i].node.split(/(\r\n|\r|\n)/g);
                    for (var j = 0; j < arrs.length; j++) {
                        var aAudioText = arrs[j].trim();
                        if (aAudioText) {
                            while (aAudioText.length >= num) {
                                var arr = [];
                                for (var k in aAudioText) {
                                    arr.push(aAudioText[k]);
                                    if (arr.join('').length >= num) {
                                        arr.pop();
                                        break;
                                    }
                                }
                                var pos = arr.join('').length;
                                textArray.push({ text: aAudioText.slice(0, pos), index: nodes[i].index });
                                aAudioText = aAudioText.slice(pos);
                            }
                        }
                        aAudioText && textArray.push({ text: aAudioText, index: nodes[i].index });
                    }
                }
                for (var i = 0; i < textArray.length; i++) {
                    var address = api + encodeURIComponent(textArray[i].text) + '&tk=' + getTk(textArray[i].text);
                    audioArray.unshift(address);
                }
                audio.preload = true;
                audio.controls = true;
                audio.src = audioArray.pop();
                audio.addEventListener('ended', playEndedHandler);
                audio.addEventListener('error', playErrorHandler);
                audio.loop = false;
                audio.play();
                stopped = false;
                var reader = textArray.shift();
                var str = ttsArr.slice(0, reader.index).join("\n");
                var strollTo = $('form.i18n textarea[name="' + ttsName + '"]')[0].scrollHeight;
                $('form.i18n textarea[name="' + ttsName + '"]').stop().animate({
                    scrollTop: Math.max(strollTo * reader.index / (ttsArr.length - 1) - 61.8, 0)
                });
                setSelectedText($('form.i18n textarea[name="' + ttsName + '"]')[0], str.length + (reader.index ? 1 : 0), str.length + (reader.index ? 1 : 0) + ttsArr[reader.index].length);
            } else {
                audio.play();
            }
        }

        // 继续播放
        function playContinueHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-play').addClass('layui-icon-pause').removeClass('layui-icon-play');
            audio.play();
        }

        // 播放暂停
        function playPauseHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-pause').addClass('layui-icon-play').removeClass('layui-icon-pause');
            audio.pause();
        }

        // 播放停止
        function playStopHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-play').remove();
            $('form.i18n .speak-voice').children('button.layui-icon-pause').remove();
            $('form.i18n .speak-voice').children('button.layui-icon-mute').addClass('layui-icon-speaker layui-btn-primary').removeClass('layui-icon-mute');
            audio.pause();
            audio.removeEventListener('ended', playEndedHandler);
            audio.removeEventListener('error', playErrorHandler);
            audioArray = [];
            stopped = true;
            textArray = [];
        }

        // 播放结束处理
        function playEndedHandler() {
            playErrors = 0;
            if (textArray.length > 0) {
                audio.src = audioArray.pop();
                audio.play();
                var reader = textArray.shift();
                var str = ttsArr.slice(0, reader.index).join("\n");
                var strollTo = $('form.i18n textarea[name="' + ttsName + '"]')[0].scrollHeight;
                $('form.i18n textarea[name="' + ttsName + '"]').stop().animate({
                    scrollTop: Math.max(strollTo * reader.index / (ttsArr.length - 1) - 61.8, 0)
                });
                setSelectedText($('form.i18n textarea[name="' + ttsName + '"]')[0], str.length + (reader.index ? 1 : 0), str.length + (reader.index ? 1 : 0) + ttsArr[reader.index].length);
            } else {
                playStopHander();
                layer.msg('{$localize.voice_reading_finished}', { icon: 1 });
            }
        }

        // 播放错误处理
        function playErrorHandler() {
            playErrorTimer && clearTimeout(playErrorTimer);
            playErrorTimer = setTimeout(function () {
                if (playErrors % 10 < 9) {
                    playErrors++;
                    audio.src = audio.src.split('&random=')[0] + '&random=' + new Date().getTime();
                    audio.play();
                } else {
                    clearTimeout(playErrorTimer);
                    playErrorTimer = null;
                    playErrors = 0;
                    playStopHander();
                    layer.alert('Audio error code: ' + audio.error.code, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] });
                }
            }, 3000 + Math.ceil(Math.random() * 2000));
        }

        // 修复翻译
        function repair_translate(html, trans) {
            var obj = {
                tag: [],
                txt: [],
                len: []
            }
            var tags = html.match(/<[^>]*>/g) || [];
            var txts = html.split(/<[^>]*>/) || [];
            for (var i = 0; i < tags.length; i++) {
                obj.txt.push(txts[i]);
                obj.tag.push(tags[i]);
                obj.len.push(txts[i].split('\n').length);
            }
            obj.txt.push(txts[tags.length]);
            obj.len.push(txts[tags.length].split('\n').length);
            var i = 0;
            var j = 0;
            var res = [];
            var arr = [];
            while ((arr = trans.split('\n').slice(i, i + obj.len[j])).length) {
                res.push(arr.join('\n'));
                if (j < obj.tag.length) {
                    if (obj.tag[j].match(/<strong>|<span[^>]*>/)) res.push(' ');
                    res.push(obj.tag[j]);
                    if (obj.tag[j].match(/<\/strong>|<\/span[^>]*>/)) res.push(' ');
                }
                i += obj.len[j];
                j++;
            }
            result = res.join('');
            result = result.replace(/(<strong>)\s+(<span[^>]*>)/gi, '$1$2');
            result = result.replace(/(<\/span>)\s+(<\/strong>)/gi, '$1$2');
            result = result.replace(/(<span[^>]*>)\s+(<strong>)/gi, '$1$2');
            result = result.replace(/(<\/strong>)\s+(<\/span>)/gi, '$1$2');
            return result;
        }

        // 国际化翻译
        $('form .i18n-tran').click(function () {
            var slop = $(this).parent().parent().parent().find('.i18n-sl');
            var tlop = $(this).parent().parent().parent().find('.i18n-tl');
            var tlang = $(this).parent().parent().parent().parent().parent().find('.i18n-lang').val();
            if (!tlang) return layer.msg('{$localize.please_select_language}', { icon: 2 });
            var q = '';
            var o = [];
            if (slop.children('option').length) {
                q = slop.children('option:selected').text().replace(/\s*┠\s*/, '').trim();
            } else if (slop.children('input[type="checkbox"]').length) {
                q = slop.children('input[type="checkbox"]:checked').map(function () {
                    return $(this).attr('title').trim();
                }).get().join('\n');
            } else if (slop.hasClass('ke-editor') && window.editor_1) {
                q = window.editor_1.html();
            } else {
                q = slop.val().trim();
            }
            var loading = layer.load(2);
            $.ajax({
                url: translate_api,
                type: 'post',
                dataType: 'json',
                data: {
                    client: 'gtx',
                    dt: 't',
                    dj: 1,
                    ie: 'UTF-8',
                    oe: 'UTF-8',
                    sl: 'zh-CN',
                    tl: tlang,
                    tk: getTk(q),
                    q: q
                },
                success: function (res) {
                    layer.close(loading);
                    if (res && res.sentences) {
                        var resText = $.map(res.sentences, function (el) {
                            return el.trans;
                        }).join("");
                        if (!tlop.hasClass('ke-editor')) {
                            resText = resText.replace(/"/g, '');
                        }
                        if (tlop.children('option').length) {
                            var selected = tlop.children('option:contains("' + resText + '")').val();
                            var selectIndex = slop.children('option:selected').index();
                            if (selected) {
                                tlop.siblings('div.layui-form-select').find('dl').find('dd[lay-value="' + selected + '"]').removeAttr('data-tran').click();
                            } else if (selectIndex) {
                                tlop.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).attr('data-tran', resText.trim());
                            }
                        } else if (tlop.children('input[type="checkbox"]').length) {
                            var resArr = resText.split('\n');
                            var inputText = '';
                            while (resArr.length) {
                                var item = resArr.shift().trim();
                                if (tlop.children('input[title="' + item + '"]').length) {
                                    tlop.children('input[title="' + item + '"]').each(function () {
                                        if (!$(this).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                            $(this).next('div.layui-form-checkbox').click();
                                        }
                                    });
                                } else {
                                    if (inputText) {
                                        inputText += ',';
                                    }
                                    inputText += item;
                                }
                            }
                            tlop.parent().parent().find('input[type="text"]').val(inputText);
                        } else if (tlop.hasClass('ke-editor') && window.editor1) {
                            window.editor1.html(resText);
                        } else {
                            if (tlop.attr('name') == 'tags') {
                                tlop.val(resText.split('\n').join(','));
                            } else {
                                tlop.val(resText);
                            }
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    layer.close(loading);
                    layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                },
            });
        });

        // 一键填充翻译
        $('form .fill-translate').click(function () {
            var tlang = $(this).parent().find('.i18n-lang').val();
            var arr = [];
            if (!tlang) return layer.msg('{$localize.please_select_language}', { icon: 2 });
            $('form .i18n-tran').each(function (i, elem) {
                var slop = $(elem).parent().parent().parent().find('.i18n-sl');
                var tlop = $(elem).parent().parent().parent().find('.i18n-tl');
                arr.push({ slop: slop, tlop: tlop })
            });
            var loading = layer.load(2);
            var qArr = [];
            $.each(arr, function (i, obj) {
                if (obj.slop.children('option').length) {
                    qArr.push(obj.slop.children('option:selected').text().replace(/\s*┠\s*/, '').trim());
                } else if (obj.slop.children('input[type="checkbox"]').length) {
                    qArr.push(obj.slop.children('input[type="checkbox"]:checked').map(function () {
                        return $(this).attr('title').trim();
                    }).get().join('\n'));
                } else if (obj.slop.hasClass('ke-editor') && window.editor_1) {
                    qArr.push(window.editor_1.html().split(/<[^>]*>/).join('\n'));
                } else {
                    qArr.push(obj.slop.val().trim());
                }
            });
            $.ajax({
                url: translate_api,
                type: 'post',
                dataType: 'json',
                data: {
                    client: 'gtx',
                    dt: 't',
                    dj: 1,
                    ie: 'UTF-8',
                    oe: 'UTF-8',
                    sl: 'zh-CN',
                    tl: tlang,
                    tk: getTk(qArr.join('\n')),
                    q: qArr.join('\n')
                },
                success: function (res) {
                    layer.close(loading);
                    if (res && res.sentences) {
                        var resTexts = $.map(res.sentences, function (el) {
                            return el.trans;
                        }).join("");
                        var resArrs = resTexts.split('\n');
                        $.each(arr, function (i, obj) {
                            var unitArr = [];
                            for (var j = 0; j < qArr[i].split('\n').length; j++) {
                                unitArr.push(resArrs.shift());
                            }
                            var resText = unitArr.join('\n');
                            if (!obj.tlop.hasClass('ke-editor')) {
                                resText = resText.replace(/"/g, '');
                            }
                            if (obj.tlop.children('option').length) {
                                var selected = obj.tlop.children('option:contains("' + resText + '")').val();
                                var selectIndex = obj.slop.children('option:selected').index();
                                if (selected) {
                                    obj.tlop.siblings('div.layui-form-select').find('dl').find('dd[lay-value="' + selected + '"]').removeAttr('data-tran').click();
                                } else if (selectIndex) {
                                    obj.tlop.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).attr('data-tran', resText.trim());
                                }
                            } else if (obj.tlop.children('input[type="checkbox"]').length) {
                                var resArr = resText.split('\n');
                                var inputText = '';
                                while (resArr.length) {
                                    var item = resArr.shift().trim();
                                    if (obj.tlop.children('input[title="' + item + '"]').length) {
                                        obj.tlop.children('input[title="' + item + '"]').each(function () {
                                            if (!$(this).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                                $(this).next('div.layui-form-checkbox').click();
                                            }
                                        });
                                    } else {
                                        if (inputText) {
                                            inputText += ',';
                                        }
                                        inputText += item;
                                    }
                                }
                                obj.tlop.parent().parent().find('input[type="text"]').val(inputText);
                            } else if (obj.tlop.hasClass('ke-editor') && window.editor1) {
                                window.editor1.html(repair_translate(window.editor_1.html(), resText));
                            } else {
                                if (obj.tlop.attr('name') == 'tags') {
                                    obj.tlop.val(resText.split('\n').join(','));
                                } else {
                                    obj.tlop.val(resText);
                                }
                            }
                        });
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    layer.close(loading);
                    layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                },
            });
        });

        // 别名翻译
        $('form .translate-slug').click(function () {
            var _this = $(this);
            var title = $('form input[name="title"], form input[name="name"]');
            var slugField = $('form input[name="slug"]');
            if (title.val().trim() == '') return layer.msg('{$localize.untitled}', { icon: 2 });
            if ('Pinyin' in window && window.Pinyin.isSupported() && 'navigator' in window && !window.navigator.onLine) {
                // 离线转拼音
                var pinyin = '';
                var tokens = Pinyin.parse(title.val().trim());
                var lastToken;
                tokens.forEach(function (v, i) {
                    if (v.type === 2) {
                        var formatTarget = v.target ? v.target.toLowerCase() : '';
                        pinyin += pinyin && !/\n|\s/.test(lastToken.target) ? ' ' + formatTarget : formatTarget;
                    } else {
                        pinyin += (lastToken && lastToken.type === 2 ? ' ' : '') + v.target;
                    }
                    lastToken = v;
                });
                slugField.val(pinyin);
            } else {
                // 否则使用接口（需联网）转英语
                icon = new Image();
                icon.src = translate_api.split('//')[0] + '//' + translate_api.split('//')[1].split('/')[0] + '/favicon.ico?t=' + new Date().getTime();
                _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                var timer = setTimeout(function () {
                    icon.onerror = icon.onload = null;
                    proxy_translate();
                }, 3000);
                icon.onerror = function () {
                    clearTimeout(timer);
                    timer = null;
                    proxy_translate();
                }
                icon.onload = function () {
                    clearTimeout(timer);
                    timer = null;
                    google_translate();
                }
                function google_translate() {
                    $.ajax({
                        url: translate_api,
                        type: 'post',
                        dataType: 'json',
                        data: {
                            client: 'gtx',
                            dt: 't',
                            dj: 1,
                            ie: 'UTF-8',
                            oe: 'UTF-8',
                            sl: 'zh-CN',
                            tl: 'en',
                            tk: getTk(title.val().trim()),
                            q: title.val().trim()
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.sentences) {
                                slugField.val($.map(res.sentences, function (el) {
                                    return el.trans.replace(/[\W]/g, ' ');
                                }).join(' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
                function proxy_translate(text) {
                    $.ajax({
                        url: 'https://api.translate.zvo.cn/translate.json',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            from: 'chinese_simplified',
                            to: 'english',
                            text: JSON.stringify([title.val().trim()])
                        },
                        beforeSend: function () {
                            _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.result) {
                                slugField.val(res.text.join(' ').replace(/[\W]/g, ' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
            }
        });

        // 字数统计
        var characters_count = function () {
            if ($('form .characters-count').length) {
                $('form .characters-count').each(function (i, elem) {
                    if ($(elem).prev().val().trim().length) {
                        var str = $(elem).prev().val().trim();
                        var len = str.length;
                        for (var j in str) {
                            if (str[j].charCodeAt(0).toString(16).length == 4) len += 1;
                        }
                        $(elem).html('<span style="color:#f00;font-weight:bold">' + len + '</span> ( ≤ ' + (i == 0 ? '60' : '140') + ' characters)');
                    } else {
                        $(elem).html('');
                    }
                });
            }
        }
        characters_count();
        $('form input[name="seo_title"], form textarea[name="seo_description"]').on('keyup change', characters_count);

        // Baidu 关键词建议
        window.bdsug = {
            sug: function (data) {
                $('form .keywords-suggest.baidu').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                if (data && data.s.length) {
                    var arr = [];
                    for (var i = 0; i < data.s.length; i++) {
                        arr.push('<button type="button" class="layui-btn layui-btn-primary layui-btn-sm suggest-item">' + data.s[i] + '</button>');
                    }
                    $('form .keywords-suggest.baidu').parent().parent().find('.suggest-result').addClass('layui-input-block').html('<fieldset class="layui-elem-field"><div class="layui-field-box">' + arr.join('\n') + '</div></fieldset>');
                } else {
                    $('form .keywords-suggest.baidu').parent().parent().find('.suggest-result').removeClass('layui-input-block').html('');
                }
            }
        }

        // Google 关键词建议
        window.google = {
            ac: {
                h: function (data) {
                    $('form .keywords-suggest.google').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    if (data && data[1].length) {
                        var arr = [];
                        for (var i = 0; i < data[1].length; i++) {
                            arr.push('<button type="button" class="layui-btn layui-btn-primary layui-btn-sm suggest-item">' + data[1][i][0] + '</button>');
                        }
                        $('form .keywords-suggest.google').parent().parent().find('.suggest-result').addClass('layui-input-block').html('<fieldset class="layui-elem-field"><div class="layui-field-box">' + arr.join('\n') + '</div></fieldset>');
                    } else {
                        $('form .keywords-suggest.google').parent().parent().find('.suggest-result').removeClass('layui-input-block').html('');
                    }
                }
            }
        }
        $('form .keywords-suggest').click(function () {
            var word = $('form input[name="title"], form input[name="name"], form input[name="webName"]').val().trim();
            if (word == '') return layer.msg('{$localize.untitled}', { icon: 2 });
            $(this).parent().parent().find('.suggest-result').removeClass('layui-input-block').html('')
            $(this).addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
            // 百度关键字建议
            if ($(this).hasClass('baidu')) {
                $.ajax({
                    url: 'https://suggestion.baidu.com/su',
                    type: 'get',
                    dataType: 'jsonp',
                    timeout: 5000,
                    data: {
                        wd: word,
                        ie: 'UTF-8',
                        cb: 'window.bdsug.sug'
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        $('form .keywords-suggest').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    },
                });
            }
            // 谷歌关键字建议
            if ($(this).hasClass('google')) {
                $.ajax({
                    url: 'https://suggestqueries.google.com/complete/search',
                    type: 'get',
                    dataType: 'jsonp',
                    data: {
                        hl: lang,
                        client: 'youtube',
                        q: word,
                        ie: 'UTF-8',
                        jsonp: 'window.google.ac.h'
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        $('form .keywords-suggest').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    },
                });
                // $.ajax({
                //     url: suggest_api,
                //     type: 'get',
                //     dataType: 'text/xml',
                //     data: {
                //         hl: lang,
                //         q: word,
                //         ie: 'UTF-8',
                //         output: 'toolbar'
                //     },
                //     success: function (res) {},
                //     error: function (XMLHttpRequest, textStatus) {
                //         layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                //     },
                // });
            }
        });

        // 关键词建议结果
        $('form .suggest-result').on('click', '.suggest-item', function () {
            var title = $('form input[name="seo_title"]');
            var discription = $('form textarea[name="seo_description"]');
            if (title.val().trim()) {
                title.val(title.val().trim() + '-');
            }
            title.val(title.val().trim() + $(this).text());
            if (discription.val().trim()) {
                discription.val(discription.val().trim() + (lang.match(/^zh-/) ? '，' : ','));
            }
            discription.val(discription.val().trim() + $(this).text());
            $(this).addClass('layui-btn-disabled').attr('disabled', true);
            characters_count();
        });

        // 获取选中文本
        function getSelectedText(inputDom) {
            if (window.getSelection) {
                if (inputDom.selectionStart != undefined && inputDom.selectionEnd != undefined) {
                    return inputDom.value.substring(inputDom.selectionStart, inputDom.selectionEnd);
                } else {
                    return "";
                }
            } else if (document.selection) {
                return document.selection.createRange().text;
            } else {
                return "";
            }
        }

        // 设置选中的文本高亮
        function setSelectedText(inputDom, startIndex, endIndex) {
            if (inputDom.setSelectionRange) {
                inputDom.setSelectionRange(startIndex, endIndex);
            } else if (inputDom.createTextRange) {
                var range = inputDom.createTextRange();
                range.collapse(true);
                range.moveStart('character', startIndex);
                range.moveEnd('character', endIndex - startIndex - 1);
                range.select();
            }
            inputDom.focus();
        }

        // 谷歌翻译tk算法
        function getTk(a) {
            var tkk = '406398.2087938574', e = tkk.split('.'), h = Number(e[0]) || 0, g = [], d = 0, i, j;
            for (var f = 0; f < a.length; f++) {
                var c = a.charCodeAt(f);
                128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
            }
            a = h;
            for (var d = 0; d < g.length; d++) {
                a += g[d];
                i = '+-a^+6';
                for (var k = 0; k < i.length - 2; k += 3) {
                    j = i.charAt(k + 2);
                    j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                    j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                    a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
                }
            }
            i = '+-3^+b+-f';
            for (var k = 0; k < i.length - 2; k += 3) {
                j = i.charAt(k + 2);
                j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
            }
            a ^= Number(e[1]) || 0;
            0 > a && (a = (a & 2147483647) + 2147483648);
            a %= 1E6;
            return a.toString() + '.' + (a ^ h)
        }
    });
</script>